package com.meilai.project.service.middleware.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.entity.middleware.Attachment;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.middleware.AttachmentMapper;
import com.meilai.project.service.middleware.AttachmentService;
import com.meilai.project.util.DateUtil;
import com.meilai.project.util.OssUtil;
import com.meilai.project.vo.app.UploadBackVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@Service
@Slf4j
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements AttachmentService {

    @Autowired
    private OssUtil ossUtil;

//    @Autowired
//    private RedisTemplate redisTemplate;

    /**
     * 存储一个文件对象
     *
     * @param inputStream   文件输入流
     * @param contentLength 文件长度
     * @param contentType   文件类型
     * @param fileName      文件索引名
     */
    @Override
    public String store(InputStream inputStream, long contentLength, String contentType, String fileName) {

        String key = generateKey(fileName);
        ossUtil.store(inputStream, contentLength, contentType, key);

        String url = generateUrl(key);
        Attachment attachment = new Attachment();
        attachment.setName(fileName);
        attachment.setSize((int) contentLength);
        attachment.setType(contentType);
        attachment.setFile_name(key);
        attachment.setUrl(url);
        baseMapper.insert(attachment);

        return url;
    }

    @Override
    public UploadBackVO storeBackVO(InputStream inputStream, long contentLength, String contentType, String fileName) {
        UploadBackVO vo = new UploadBackVO();

        String key = generateKey(fileName);
        ossUtil.store(inputStream, contentLength, contentType, key);

        String url = generateUrl(key);
        Attachment attachment = new Attachment();
        attachment.setName(fileName);
        attachment.setSize((int) contentLength);
        attachment.setType(contentType);
        attachment.setFile_name(key);
        attachment.setUrl(url);
        baseMapper.insert(attachment);

        BeanUtils.copyProperties(attachment, vo);

        return vo;
    }

    /**
     * 存储一个文件对象
     *
     * @param inputStream   文件输入流
     * @param contentLength 文件长度
     * @param contentType   文件类型
     * @param fileName      文件索引名
     */
    @Override
    public String store2(String tenantName,InputStream inputStream, long contentLength, String contentType, String fileName) {

        String key = generateKey(fileName);
        ossUtil.store(inputStream, contentLength, contentType, key);

        String url = generateUrl(key);
        Attachment attachment = new Attachment();
        attachment.setName(fileName);
        attachment.setSize((int) contentLength);
        attachment.setType(contentType);
        attachment.setFile_name(key);
        attachment.setUrl(url);
        baseMapper.insert(attachment);

        return url;
    }

    /**
     * 存储一个文件对象
     *
     * @param inputStream 文件输入流
     * @param fileName    文件索引名
     */
    @Override
    public String storeSimple(InputStream inputStream, String fileName) {

        String key = generateKey(fileName);
        ossUtil.storeSimple(inputStream, key);
        String url = generateUrl(key);

        Attachment attachment = new Attachment();
        attachment.setName(fileName);
        attachment.setFile_name(key);
        attachment.setUrl(url);
        baseMapper.insert(attachment);

        return url;
    }

    @Override
    public UploadBackVO storeSimpleBackVO(InputStream inputStream, String fileName) {
        UploadBackVO vo = new UploadBackVO();

        String key = generateKey(fileName);
        ossUtil.storeSimple(inputStream, key);
        String url = generateUrl(key);

        Attachment attachment = new Attachment();
        attachment.setName(fileName);
        attachment.setFile_name(key);
        attachment.setUrl(url);
        baseMapper.insert(attachment);

        BeanUtils.copyProperties(attachment, vo);

        return vo;
    }

//    @Override
//    public String storeToll(MultipartFile file, HttpSession session, HttpServletRequest request) throws Exception {
//        String originalFilename = file.getOriginalFilename();
//        long contentLength = file.getSize();
//        String contentType = file.getContentType();
//
//        String key = generateKey(originalFilename);
//        ossAliyunUtil.storeToll(file.getInputStream(), key, contentLength, contentType, session, request);
//        String url = generateUrl(key);
//
//        Attachment attachment = new Attachment();
//        attachment.setName(originalFilename);
//        attachment.setSize((int) contentLength);
//        attachment.setType(contentType);
//        attachment.setFile_name(key);
//        attachment.setUrl(url);
//        baseMapper.insert(attachment);
//
//        return url;
//    }

    @Override
    public Boolean deleteOne(String keyName) {
        Attachment temp = null;
        try {
            temp = getOne(new QueryWrapper<Attachment>().eq("file_name", keyName), true);
        }catch(Exception e){
            log.error("删除附件，查询失败",e);
            throw new CommonException("删除失败，请联系管理员");
        }
        if(temp != null){
            ossUtil.delete(keyName);
            return update(new UpdateWrapper<Attachment>().set("deleted_at", LocalDateTime.now()).eq("id",temp.getId()));
        }else{
            return true;
        }
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        return DateUtil.getFileName() + (index >= 0 ? originalFilename.substring(index) : "");
    }

    private String generateUrl(String keyName) {
        return ossUtil.generateUrl(keyName);
    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }


//    public String getQRCode(String scene, String path) {
//        String access_token = getAccessToken();
//        Map<String, String> map = new HashMap<>();
//        map.put("scene", scene);
//        map.put("page", path);
//        byte[] ret = OkHttpUtil.postJsonParams("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token, JSON.toJSONString(map));
//        log.info("获取二维码：{}", ret);
//        log.info("获取二维码返回长度：{}", ret.length);
//        InputStream inputStream = new ByteArrayInputStream(ret);
//        return storeSimple(inputStream, "qrcode/" + generateNonceStr() + ".jpg");
//    }
//
//    public String getAccessToken() {
//
//        if( null != redisTemplate.opsForValue().get("MINIPROGRAM_ACCESS_TOKEN") ) {
//            String token = redisTemplate.opsForValue().get("MINIPROGRAM_ACCESS_TOKEN").toString();
//            if(!org.apache.commons.lang.StringUtils.isEmpty(token)) {
//                return token;
//            }
//        }
//
//        String ret = OkHttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+
//                WxProgramConfig.APPID +"&secret=" + WxProgramConfig.SECRET, new HashMap<>());
//        log.info("获取大奥的accessToken返回值：{}", ret);
//        JSONObject jsonObject = JSON.parseObject(ret);
//        String access_token = jsonObject.getString("access_token");
//        redisTemplate.opsForValue().set("MINIPROGRAM_ACCESS_TOKEN", access_token, 60, TimeUnit.MINUTES);
//        return access_token;
//    }
}
